<template>
  <div ref="viewScaleIframeRef" class="cjui-view-scale-iframe">
    <iframe
      frameborder="0"
      :style="{
        width: `${iframeWidthRO}px`,
        height: `${iframeHeightRO}px`,
        transform: `scale(${iframeScale})`,
      }"
      v-bind="$attrs"
    >
    </iframe>
  </div>
</template>

<script lang="ts" setup>
import { debounceFun } from './helper/debounceFun'

defineOptions({
  name: 'CjuiViewScaleIframe',
})

interface Props {
  iframeWidth: number
  iframeHeight: number
}
const props = withDefaults(defineProps<Props>(), {
  iframeWidth: 1920,
  iframeHeight: 1080
})

const viewScaleIframeRef = useTemplateRef('viewScaleIframeRef') 
const iframeScale = ref(1) 
const iframeWidthRO = ref(props.iframeWidth) 
const iframeHeightRO = ref(props.iframeHeight) 
const getIframeScale = () => { 
  if (viewScaleIframeRef.value) { 
    iframeScale.value = viewScaleIframeRef.value.clientWidth / props.iframeWidth
    iframeHeightRO.value = viewScaleIframeRef.value.clientHeight / iframeScale.value
  } 
} 
const getIframeScaleDebounce = debounceFun(getIframeScale) 
const ro = new ResizeObserver((_entries) => getIframeScaleDebounce()) 
  
onMounted(() => { 
  getIframeScale() 
  ro.observe(viewScaleIframeRef.value) 
}) 
onBeforeUnmount(() => { 
  ro.disconnect() 
})
</script>

<style lang="scss" scoped>
.cjui-view-scale-iframe {
  width: 100%;
  height: 100%;
  overflow: hidden;
  iframe {
    transform-origin: left top;
  }
}
</style>
